package com.shujia.spark.mllib

import org.apache.spark.ml.classification.LogisticRegressionModel
import org.apache.spark.ml.linalg
import org.apache.spark.ml.linalg.Vectors
import org.apache.spark.sql.{DataFrame, Row, SparkSession}

object Demo7UseImageModel {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession
      .builder()
      .master("local[8]")
      .appName("person")
      .config("spark.sql.shuffle.partitions", 1)
      .getOrCreate()

    import spark.implicits._

    /**
      * 读取需要识别的图片
      *
      */

    val imageData: DataFrame = spark
      .read
      .format("image")
      .load("D:\\课件\\机器学习数据\\手写数字\\test2")
      .select($"image.origin", $"image.data")

    /**
      * 需要将图片转换成和训练集一样的数据
      *
      */

    val nameAndVector: DataFrame = imageData.map {
      case Row(origin: String, data: Array[Byte]) =>
        val comData: Array[Double] = data
          .map(byte => byte.toInt)
          //归一化，将数据转换成0或者1
          .map(i => {
          if (i >= 0) {
            0.0
          } else {
            1.0
          }
        })
        //将特征转换成向量
        val vector: linalg.Vector = Vectors.dense(comData)

        //取出图片的名称
        val name: String = origin.split("/").last

        (name, vector)
    }.toDF("name", "features")


    /**
      * 加载模型
      *
      */

    val model: LogisticRegressionModel = LogisticRegressionModel.load("data/image_model")

    val frame: DataFrame = model.transform(nameAndVector)

    frame.show(1000)

  }

}
